from querier.esquerier import ElasticSearchQuerier

WORDCLOUD_TOP_N = 100


class JDShopWordCloudQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(JDShopWordCloudQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args['shop_id']
        res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
        if res['found']:
            keywords = res['_source']['keywords'][0:WORDCLOUD_TOP_N]
            weight = res['_source']['weight'][0:WORDCLOUD_TOP_N]
            categories = res['_source']['categories']
            shop_url = res['_source']['shop_url']
            shop_name = res['_source']['shop_name']
            # shop_id = res['_source']['shop_id'],
            shop_type = res['_source']['shop_type']
            goods_score = res['_source']['goods_score']
            service_score = res['_source']['service_score']
            effective_score = res['_source']['effective_score']
            star_score = res['_source']['star_score']
            shop_start_date = res['_source']['shop_start_date']
            shop_end_date = res['_source']['shop_end_date']
            cps_shop_url = res['_source']['cps_shop_url']
            commission_expense = res['_source']['commission_expense']
            thirty_order_count = res['_source']['thirty_order_count']
            avg_commission_ratio = res['_source']['avg_commission_ratio']
            cover_url = res['_source']['cover_url']
            created_at = res['_source']['created_at']
            updated_at = res['_source']['updated_at']
            len_keywords = len(keywords)
            len_weight = len(weight)
            length = len_keywords if len_keywords <= len_weight else len_weight
            ret = [{"text": keywords[i], "weight": weight[i]} for i in range(0, length)]

            return {

                'shop_name': shop_name,
                'categories': categories,
                'thirty_order_count': thirty_order_count,
                'avg_commission_ratio': avg_commission_ratio,
                'shop_url': shop_url,
                'shop_type': shop_type,
                'goods_score': goods_score,
                'service_score': service_score,
                'effective_score': effective_score,
                'star_score': star_score,
                'commission_expense': commission_expense,
                'shop_start_date': shop_start_date,
                'shop_end_date': shop_end_date,
                'cover_url': cover_url,
                'cps_shop_url': cps_shop_url,
                'keywords': ret,
                'created_at': created_at,
                'updated_at': updated_at
            }
        return {'message': 'shop_id=%s not found.' % id_}

    def _build_query(self, args): pass

    def _build_result(self, es_result, param): pass
